package com.treasure.mall.zbqmallmanager.controller.integral;

import com.treasure.mall.biz.dto.condition.CommonCondition;
import com.treasure.mall.biz.dto.integral.ProductSaveDTO;
import com.treasure.mall.biz.entity.integral.IntegralProductPO;
import com.treasure.mall.biz.service.core.integral.IntegralProductService;
import com.treasure.mall.zbq.common.base.ApiResult;
import com.treasure.mall.zbq.common.constant.Constant;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

/**
 * @author allan
 * @version 1.0.0
 * @date 2020/8/24
 */
@Controller
@RequestMapping("/integral/product")
public class IntegralProductController {
    @Autowired
    private IntegralProductService productService;

    @GetMapping("/list")
    public String list(
            @ModelAttribute("condition") CommonCondition condition,
            @RequestParam(required = false, defaultValue = "1") int pageIndex,
            Model model
    ) {
        Page<IntegralProductPO> productPOS = productService.findAll(pageIndex, Constant.DEFAULT_PAGE_SIZE, condition);

        model.addAttribute("pageIndex", pageIndex);
        model.addAttribute("totalRecords", productPOS.getTotalElements());
        model.addAttribute("totalPages", productPOS.getTotalPages());
        model.addAttribute("list", productPOS.getContent());

        return "integral/product_list";
    }

    @GetMapping("/save")
    public String save(long productId, Model model) {
        IntegralProductPO po;
        if (productId > 0) {
            po = productService.findById(productId);
        } else {
            po = new IntegralProductPO();
        }

        model.addAttribute("po", po);

        return "integral/product_edit";
    }

    @PostMapping("/save")
    @ResponseBody
    public ApiResult save(ProductSaveDTO saveDTO) {
        productService.save(saveDTO);

        return ApiResult.ok();
    }

    @PostMapping("/publishToggle")
    @ResponseBody
    public ApiResult publishToggle(Long productId) {
        productService.publishedToggle(productId);

        return ApiResult.ok();
    }

    @PostMapping("/modifyStore")
    @ResponseBody
    public ApiResult modifyStore(Long productId, int num) {
        if (num > 0) {
            productService.addStore(productId, num);
        } else {
            productService.minusStore(productId, num * -1);
        }

        return ApiResult.ok();
    }
}
